<?php
/**--------------------
 * Date: 2018/2/2
 * FileName:QuestionsModel.php
 * ProjectName:ZhiShiRongYao
 * -------------------- */


namespace app\common\model;


use think\Model;
use think\Db;

/**@protected title title */
class QuestionsModel extends Model
{

    protected $name = 'questions';
    /**
     * @var bool 开启自动写入时间戳字段
     */
    protected $autoWriteTimestamp = true;

    /**
     * @param int     $subject_id 科目id
     * @param string  $title      标题
     * @param  string $answer     序列化
     * @param  int    $user_id    用户id
     * @param  string $user_name  用户名
     * @param int     $status     状态 0:审核中，1=>已通过，2：未通过
     * @param int     $source_type
     *
     * @return int|string
     */
    public static function addQuestions($subject_id, $title, $answer, $user_id, $user_name, $status = 0, $source_type = 0)
    {
        $data = [
            'subject_id'  => $subject_id,
            'title'       => $title,
            'answer'      => $answer,
            'user_id'     => $user_id,
            'source_type' => $source_type,
            'user_name'   => $user_name,
            'status'      => $status,
            'create_time' => time(),
        ];
        return self::insert($data);
    }

    /**
     * 获取用户pk题目
     *
     * @throws \think\exception\DbException 数据库报错
     * @return string
     */
    public function getQuestionsPk($params = [])
    {
        $subject_info   = [];
        $is_auto_answer = !empty($params['is_auto_answer']) ? $params['is_auto_answer'] : 0;
        $user_id = !empty($params['user_id']) ? $params['user_id'] : 0;
        $to_user_id = !empty($params['to_user_id']) ? $params['to_user_id'] : 0;
        //$aid = !empty($params['aid']) ? $params['aid'] : 0;
        $aid = db('activity')->where(['status'=>1])->value('id');//正在时行的活动
        $where=[];
        if(isset($params['grad_id'])&&$params['grad_id']!=0 && config('is_grad_questions')==1){
            $where['q.grad_id']=$params['grad_id'];
        }
        $where['q.status']=1;
        $questions_five = Db::name('questions q')
                            ->join('knowledge_subject k', 'q.subject_id=k.id')
                            ->where($where)
                            ->field('q.id,q.title,q.answer,k.name,q.subject_id,k.parent_id as subject_cate_id')
                            ->order('rand()')
                            ->limit(5)
                            ->select();

        if (count($questions_five) >= 5) {
            foreach ($questions_five as $k => $v) {
                $questions_ids[] = $v['id'];
                $question_answer = '';
                $question_answer = unserialize($v['answer']);
                shuffle($question_answer);
                $questions_five[$k]['answer'] = $question_answer;
                if ($is_auto_answer) {//机器人答题
                    //随机秒数
                    $num = [1,2,3,4,5,6];
                    $_seconds = array_rand($num, 1);
                    $robot_type=Db::name('user')->where('id',$to_user_id)->value('robot_rule_type');
                    if($robot_type){//机器人概率答题
                        $robot_rule=Db::name('robot_rule')->where('type',$robot_type)->find();
                        $robot_answer= unserialize($robot_rule['answer_right_rate']);
                        foreach ($question_answer as $key=>$value){
                            if($value['is_right']){
                                $prize_arr[$key]=intval($robot_answer[$k]['answer_right_rate']);
                            }else{
                                $prize_arr[$key]= intval(intval(100-$robot_answer[$k]['answer_right_rate'])/3);
                            } 
                        }
                        $answer_result=get_rand($prize_arr);
                        $subject_info['user_answer'][$k] = [
                            'question_id'    => $v['id'],
                            'answer_id'      => $question_answer[$answer_result]['id'],
                            'answer_val'     => $question_answer[$answer_result]['is_right'],
                            'answer_seconds' => $num[$_seconds]
                        ];
                    }else{//机器人随机答题
                        $_answer= array_rand($question_answer, 1);
                        $subject_info['user_answer'][$k] = [
                            'question_id'    => $v['id'],
                            'answer_id'      => $question_answer[$_answer]['id'],
                            'answer_val'     => $question_answer[$_answer]['is_right'],
                            'answer_seconds' => $num[$_seconds]
                        ];
                    }
                }
            }
            $data = [
                'questions_id' => implode(',', $questions_ids),
                'aid'          => $aid ? $aid:0,//活动id
                //活动ID
                'user_id'      => $user_id,
                //用户ID
                'to_user_id'   => $to_user_id,
                //目标用户ID
                'create_time'  => time()
            ];
            $res  = db('user_subject_pk')->insertGetId($data);
            if ($res) {
                $subject_info['pk_id']       = $res;
                $subject_info['score_scale'] = [
                    1  => '100',
                    2  => '90',
                    3  => '80',
                    4  => '70',
                    5  => '60',
                    6  => '50',
                    7  => '40',
                    8  => '30',
                    9  => '20',
                    10 => '10',
                ];//config('answer_question_time');
                $subject_info['subject']     = $questions_five;
                return $subject_info;
            } else {
                return -1;//'获取题目失败';
            }
        } else {
            return 0;//'题目库存不足';
        }
    }
    //排位赛扣除金币
    public function deduct_points($params = []){
        if(!$params['user_id'] && !$params['to_user_id'] &&!$params['grad_id']){
            return false;
        }
        $consume_point=db('grad')->where('id',$params['grad_id'])->value('consume_point');
        $data=[
            'points'=>['exp',"points-$consume_point"]
        ];
        $map['id'] = ['in', array($params['user_id'],$params['to_user_id'])];
        $res=db('user')->where($map)->update($data);
        //金币日志
        $user_list=db('user')->where($map)->select();
        foreach($user_list as $value){
            $data_log=[];
            $data_log=[
                'user_id'       =>$value['id'],
                'user_name'     =>$value['display_name'],
                'points'        =>'-'.$consume_point,
                'remark'        =>'排位赛扣除金币',
                'stage'         =>'pk',
                'create_time'   =>time()
            ];
            db('points_log')->insertGetId($data_log);
        }
        if($res){
            $data_msg=['status'=>1,'message'=>'扣除金币成功'];
        }else{
            $data_msg=['status'=>0,'message'=>'扣除金币失败'];
        }
        return $data_msg;
    }
    
    //道具到期时间
    public function expirationTime($time){
        $now=time();
        $exp_time=$time-$now;
        $remain = $exp_time%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        $data_time=($secs+$mins*60+$hours*60*60)*1000; 
        return $data_time;
    }
}